import 'package:flutter/material.dart';
import 'package:get/get.dart';
import '../../../models/device_model.dart';
import '../../../providers/device_provider.dart';
import '../../../providers/system_provider.dart';
import '../../../services/product_service.dart';
import '../../../repositories/device_repository.dart';
import '../../../utils/themes/app_theme_extension.dart';
import '../../../routes/app_routes.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';

class DeviceController extends GetxController {
  final DeviceProvider deviceProvider = DeviceProvider();
  final SystemProvider systemProvider = SystemProvider();
  final ProductService _productService = Get.find<ProductService>();
  final DeviceRepository _deviceRepository = Get.find<DeviceRepository>();

  // 可观察变量
  final RxBool isLoading = false.obs;
  final RxBool isRefreshing = false.obs;
  final RxBool isLoadingMore = false.obs;
  final RxBool isSearching = false.obs;
  final RxBool hasMoreData = true.obs;
  final RxList<Device> devices = <Device>[].obs;
  final RxList<Device> searchResults = <Device>[].obs;

  // 筛选变量
  final Rxn<int> filterStatus = Rxn<int>();
  final TextEditingController productKeyController = TextEditingController();

  // 分页参数
  int currentPage = 1;
  final int pageSize = 10;

  // 滚动控制器
  final ScrollController scrollController = ScrollController();

  // 视图控制
  final RxBool isGridView = true.obs;

  @override
  void onInit() {
    super.onInit();
    scrollController.addListener(_scrollListener);

    // 检查并处理从首页传入的状态参数
    if (Get.arguments != null && Get.arguments is Map) {
      final args = Get.arguments as Map;
      if (args.containsKey('status')) {
        // 直接使用数字状态值
        final status = args['status'];
        if (status is int || status is String) {
          // 如果是String类型，则尝试转换为int
          int? statusValue = status is int ? status : int.tryParse(status.toString());
          filterStatus.value = statusValue;
          debugPrint('设置设备状态筛选: $status => ${filterStatus.value}');
        }
      }
    }

    // 加载设备列表
    fetchDevices();

    // 预加载产品数据
    _preloadProductData();
  }

  // 预加载产品数据，以便获取产品名称
  Future<void> _preloadProductData() async {
    try {
      await _productService.getAllProducts();
    } catch (e) {
      debugPrint('预加载产品数据失败: $e');
    }
  }

  @override
  void onClose() {
    scrollController.removeListener(_scrollListener);
    scrollController.dispose();
    productKeyController.dispose();
    super.onClose();
  }

  // 滚动监听
  void _scrollListener() {
    if (scrollController.position.pixels >=
            scrollController.position.maxScrollExtent - 200 &&
        !isLoading.value &&
        !isLoadingMore.value &&
        hasMoreData.value) {
      loadMoreDevices();
    }
  }

  // 获取设备列表
  Future<void> fetchDevices() async {
    try {
      isLoading.value = true;
      final response = await deviceProvider.getDeviceList(
        pageNum: currentPage,
        pageSize: pageSize,
        status: filterStatus.value,
        productKey: productKeyController.text.isNotEmpty
            ? productKeyController.text
            : null,
      );

      if (currentPage == 1) {
        devices.clear();
      }

      devices.addAll(response.rows);

      // 判断是否还有更多数据
      hasMoreData.value =
          response.rows.length >= pageSize && response.total > devices.length;
      
      print('设备列表加载成功，共${devices.length}个设备');
      
    } catch (e) {
      Get.snackbar('错误', '获取设备列表失败: $e');
    } finally {
      isLoading.value = false;
      isRefreshing.value = false;
    }
  }

  // 刷新设备列表
  Future<void> refreshDevices() async {
    isRefreshing.value = true;
    currentPage = 1;
    hasMoreData.value = true;
    await fetchDevices();
    return;
  }

  // 加载更多设备
  Future<void> loadMoreDevices() async {
    if (isLoadingMore.value || !hasMoreData.value) return;

    isLoadingMore.value = true;
    currentPage++;
    try {
      final response = await deviceProvider.getDeviceList(
        pageNum: currentPage,
        pageSize: pageSize,
        status: filterStatus.value,
        productKey: productKeyController.text.isNotEmpty
            ? productKeyController.text
            : null,
      );

      if (response.rows.isNotEmpty) {
        devices.addAll(response.rows);
      }

      // 判断是否还有更多数据
      hasMoreData.value =
          response.rows.length >= pageSize && response.total > devices.length;

      if (response.rows.isEmpty) {
        hasMoreData.value = false;
      }
    } catch (e) {
      currentPage--; // 恢复页码
      Get.snackbar('错误', '加载更多设备失败: $e');
    } finally {
      isLoadingMore.value = false;
    }
  }

  // 搜索设备
  Future<void> searchDevices(String query) async {
    if (query.isEmpty) {
      searchResults.clear();
      return;
    }

    try {
      isSearching.value = true;
      // 按设备名称搜索
      final response = await deviceProvider.getDeviceList(
        pageNum: 1,
        pageSize: 20,
        deviceName: query,
      );

      // 如果按名称搜索没有结果，尝试按设备序列号搜索
      if (response.rows.isEmpty) {
        final snResponse = await deviceProvider.getDeviceList(
          pageNum: 1,
          pageSize: 20,
          deviceSn: query,
        );

        final deviceList = snResponse.rows;
        searchResults.assignAll(deviceList);
      } else {
        final deviceList = response.rows;
        searchResults.assignAll(deviceList);
      }
    } catch (e) {
      Get.snackbar('错误', '搜索设备失败: $e');
    } finally {
      isSearching.value = false;
    }
  }

  // 应用筛选器
  Future<void> applyFilters() async {
    currentPage = 1;
    hasMoreData.value = true;
    await fetchDevices();
  }

  // 重置筛选器
  void resetFilters() {
    filterStatus.value = null;
    productKeyController.clear();
    currentPage = 1;
    hasMoreData.value = true;
  }

  // 查看设备详情
  void viewDeviceDetail(int? deviceId) {
    if (deviceId != null) {
      // 先从当前设备列表查找
      Device? foundDevice = devices.firstWhereOrNull((d) => d.deviceId == deviceId);
      
      // 如果当前列表中没有找到，尝试从搜索结果中查找
      if (foundDevice == null && searchResults.isNotEmpty) {
        foundDevice = searchResults.firstWhereOrNull((d) => d.deviceId == deviceId);
      }
      
      // 如果找到了设备，传递更多信息到详情页
      if (foundDevice != null) {
        Get.toNamed('/device/detail', arguments: {
          'deviceId': deviceId,
          'deviceName': foundDevice.deviceName,
          'deviceInfo': foundDevice
        });
      } else {
        // 如果没找到，只传递ID
        Get.toNamed('/device/detail', arguments: {'deviceId': deviceId});
      }
    }
  }

  // 查看设备数据（图表形式）
  void viewDeviceData(int? deviceId) {
    if (deviceId != null) {
      // 先从当前设备列表查找
      Device? foundDevice = devices.firstWhereOrNull((d) => d.deviceId == deviceId);
      
      // 如果当前列表中没有找到，尝试从搜索结果中查找
      if (foundDevice == null && searchResults.isNotEmpty) {
        foundDevice = searchResults.firstWhereOrNull((d) => d.deviceId == deviceId);
      }
      
      // 如果找到了设备，传递设备ID和设备名称到数据页面
      if (foundDevice != null && foundDevice.deviceName != null && foundDevice.deviceName!.isNotEmpty) {
        Get.toNamed('/device/data', arguments: {
          'deviceId': deviceId,
          'deviceName': foundDevice.deviceName ?? '',
        });
      } else {
        // 如果没找到或设备名为空，只传递ID
        Get.toNamed('/device/data', arguments: {
          'deviceId': deviceId,
          'deviceName': '',
        });
      }
    }
  }

  // 查看设备数据（表格形式）
  void viewDeviceDataTable(int? deviceId) {
    if (deviceId != null) {
      // 先从当前设备列表查找
      Device? foundDevice = devices.firstWhereOrNull((d) => d.deviceId == deviceId);
      
      // 如果当前列表中没有找到，尝试从搜索结果中查找
      if (foundDevice == null && searchResults.isNotEmpty) {
        foundDevice = searchResults.firstWhereOrNull((d) => d.deviceId == deviceId);
      }
      
      // 如果找到了设备，传递设备ID和设备名称到数据表格页面
      if (foundDevice != null && foundDevice.deviceName != null && foundDevice.deviceName!.isNotEmpty) {
        Get.toNamed('/device/data_table', arguments: {
          'deviceId': deviceId,
          'deviceName': foundDevice.deviceName ?? '',
        });
      } else {
        // 如果没找到或设备名为空，只传递ID
        Get.toNamed('/device/data_table', arguments: {
          'deviceId': deviceId,
          'deviceName': '',
        });
      }
    }
  }

  // 编辑设备
  void editDevice(int deviceId) {
    // 暂未实现编辑功能
    Get.toNamed('/device/edit/$deviceId');
  }

  // 删除设备
  Future<void> deleteDevice(int deviceId) async {
    try {
      await deviceProvider.deleteDevices([deviceId]);
      Get.snackbar('成功', '设备已删除');
      refreshDevices();
    } catch (e) {
      Get.snackbar('错误', '删除设备失败: $e');
    }
  }

  // 查看设备视频监控
  void viewDeviceVideo(int? deviceId) async {
    if (deviceId != null) {
      debugPrint('===== 开始查看设备视频监控 =====');
      debugPrint('查询的设备ID: $deviceId');
      
      // 先从当前设备列表查找
      Device? foundDevice = devices.firstWhereOrNull((d) => d.deviceId == deviceId);
      
      // 如果当前列表中没有找到，尝试从搜索结果中查找
      if (foundDevice == null && searchResults.isNotEmpty) {
        foundDevice = searchResults.firstWhereOrNull((d) => d.deviceId == deviceId);
      }
      
      if (foundDevice == null) {
        debugPrint('严重错误: 未找到设备ID为 $deviceId 的设备');
        Get.snackbar('错误', '无法找到该设备');
        return;
      }
      
      debugPrint('找到设备: ${foundDevice.deviceName}');
      debugPrint('国标设备ID: "${foundDevice.wvpDeviceId}"');
      
      // 检查设备是否有国标ID
      if (foundDevice.wvpDeviceId.isNotEmpty) {
        try {
          // 1. 使用SystemProvider获取WVP设备信息
          debugPrint('【步骤1】通过API "/system/GB28181device/list?device_id=${foundDevice.wvpDeviceId}" 获取WVP设备信息');
          final gbDeviceInfo = await systemProvider.getGBDeviceInfo(foundDevice.wvpDeviceId);
          
          debugPrint('【步骤1响应】获取WVP设备信息结果: $gbDeviceInfo');
          
          if (gbDeviceInfo['code'] == 200 && gbDeviceInfo['rows'] != null && gbDeviceInfo['rows'].isNotEmpty) {
            final gbDevice = gbDeviceInfo['rows'][0];
            final gbDeviceId = gbDevice['id'].toString();
            
            debugPrint('WVP设备信息解析成功:');
            debugPrint('- 主键ID: $gbDeviceId');
            debugPrint('- 名称: ${gbDevice['name']}');
            debugPrint('- 状态: ${gbDevice['status']}');
            
            // 2. 使用SystemProvider获取通道列表
            debugPrint('【步骤2】通过API "/system/GB28181channel/list?data_device_id=$gbDeviceId" 获取通道列表');
            final channelListResponse = await systemProvider.getGBChannelList(gbDeviceId);
            
            debugPrint('【步骤2响应】获取通道列表结果: $channelListResponse');
            
            if (channelListResponse['code'] == 200 && channelListResponse['rows'] != null) {
              final channelList = channelListResponse['rows'];
              
              debugPrint('通道列表解析成功:');
              debugPrint('- 通道数量: ${channelList.length}');
              
              // 打印前3个通道的信息(如果有)
              for (var i = 0; i < channelList.length && i < 3; i++) {
                final channel = channelList[i];
                debugPrint('- 通道${i+1}: ID=${channel['id']}, 名称=${channel['name']}, 国标ID=${channel['deviceId']}');
              }
            } else {
              debugPrint('未找到通道或响应格式不正确');
            }
          } else {
            debugPrint('未找到WVP设备信息或响应格式不正确');
          }
        } catch (e) {
          debugPrint('获取WVP设备信息或通道列表出错: $e');
        }
        
        // 继续跳转到视频页面
        debugPrint('设备有国标ID，跳转到视频页面');
        Get.toNamed('/device/video', arguments: {
          'deviceId': deviceId,
          'deviceName': foundDevice.deviceName ?? '',
          'wvpDeviceId': foundDevice.wvpDeviceId
        });
      } else {
        debugPrint('设备没有国标ID');
        Get.snackbar('提示', '该设备未绑定视频监控功能');
      }
    } else {
      debugPrint('严重错误: 传入的设备ID为null');
    }
  }

  // 添加新设备
  void addNewDevice() {
    try {
      Get.toNamed('/device/add');
    } catch (e) {
      // 如果路由未定义，显示一个提示
      Get.snackbar('提示', '添加设备功能正在开发中');
    }
  }
}
